package com.cloud.wms.ui.main.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.multistate.LoadingAdapter;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseListActivity;
import com.cloud.wms.ui.main.contract.BaseInfoContract;
import com.cloud.wms.ui.main.entity.MemberEntity;
import com.cloud.wms.ui.main.entity.WarehouseEntity;
import com.cloud.wms.ui.main.presnter.BaseInfoPresenter;
import com.dylanc.loadinghelper.LoadingHelper;
import com.dylanc.loadinghelper.ViewType;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * @Author:Chen
 * @Date: 2021-01-15 15:32
 * @Description:
 */
public class BaseWarehouseActivity extends BaseListActivity<WarehouseEntity, BaseInfoPresenter> implements BaseInfoContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_pre)
    TextView tvPre;
    @BindView(R.id.tv_jump)
    TextView tvJump;
    @BindView(R.id.et_search)
    EditText etSearch;
    private int index = -1;
    private ArrayList<WarehouseEntity> warehouseList = new ArrayList<>();

    @Override
    protected int getResId() {
        return R.layout.activity_main_base;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initBar() {
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvTitle.setText("选择仓库");
        tvJump.setVisibility(View.GONE);
        tvPre.setVisibility(View.GONE);

        etSearch.setHint("查找仓库");
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchWarehouse(s);
            }
        });
        mPresenter.loadWarehouseList();
    }

    @SuppressLint("CheckResult")
    private void searchWarehouse(Editable s) {
        index = -1;
        Observable.fromIterable(warehouseList)
                .filter(warehouseInfo -> TextUtils.isEmpty(s) || warehouseInfo.getWareHouseName().contains(s))
                .toList()
                .subscribe(data -> mAdapter.setNewInstance(data));
    }

    @Override
    protected boolean isRefresh() {
        return false;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_main_base;
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(this, 2);
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(2)
                .verticalDivider(null, DensityUtils.Dp2Px(this, 12), false)
                .horizontalDivider(null, DensityUtils.Dp2Px(this, 12), false)
                .build();
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, WarehouseEntity item) {
        helper.setText(R.id.tv_info_name, item.getWareHouseName());
        CheckedTextView checkView = (CheckedTextView) helper.getView(R.id.tv_info_name);
        checkView.setChecked(index == helper.getAdapterPosition());
        if (mAdapter.getData().size() == 1) {
            index = 0;
            checkView.setChecked(true);
        }
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<WarehouseEntity, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
        if (index == position) index = -1;
        else index = position;
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
        switch (message.what) {
            case BaseInfoPresenter.WAREHOUSE:
                List<WarehouseEntity> list = (List<WarehouseEntity>) message.obj;
                warehouseList.clear();
                warehouseList.addAll(list);

                WarehouseEntity warehouseInfo = FineExApplication.component().loginCache().getWarehouseInfo();
                if (warehouseInfo != null) {
                    for (int i = 0; i < list.size(); i++) {
                        WarehouseEntity warehouseEntity = list.get(i);
                        if (warehouseInfo.getWarehouseID() == warehouseEntity.getWarehouseID()) {
                            index = i;
                            scrollToPosition(rvList, index);
                            break;
                        }
                    }
                }
                mAdapter.setNewInstance(list);
                break;
        }
    }

    @Override
    public void showEmpty() {
        mAdapter.setEmptyView(getEmptyDataView());
    }

    @Override
    public void showError() {
        mAdapter.setEmptyView(getErrorView());
    }

    protected View getEmptyDataView() {
        View notDataView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_empty, rvList, false);
        notDataView.setOnClickListener(v -> mPresenter.loadWarehouseList());
        return notDataView;
    }

    protected View getErrorView() {
        View errorView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_error, rvList, false);
        errorView.setOnClickListener(v -> mPresenter.loadWarehouseList());
        return errorView;
    }

    @OnClick(R.id.btn_next)
    public void onViewClicked() {
        if (index >= 0) {
            FineExApplication.component().loginCache().setWarehouseInfo(mAdapter.getData().get(index));
            BaseMemberActivity.start(this);
            this.finish();
        } else
            info("请选择仓库");
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, BaseWarehouseActivity.class);
        context.startActivity(intent);
    }
}
